﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command;
using MediatR;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler
{
    public class CreateRoleMenuCommendHandlers : IRequestHandler<CreateRoleMenuCommends, APIResult<object>>
    {
        private readonly IBaseRepository<RoleMenu> rolemenuRepository;
        private readonly IMapper mapper;

        public CreateRoleMenuCommendHandlers(IBaseRepository<RoleMenu> rolemenuRepository, IMapper mapper)
        {
            this.rolemenuRepository = rolemenuRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 创建角色菜单数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<object>> Handle(CreateRoleMenuCommends request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();

            //1.通过RoleId 角色ID查询所有数据批量删除
            var list = rolemenuRepository.GetAll().Where(p=>p.RoleId==request.RoleId).ToList();
            await rolemenuRepository.DelList(list);
            var rolemenus = request.MenuId.Select(x => new RoleMenu { MenuId = x, RoleId = request.RoleId })
                .ToList();

            //2.批量添加
            var res=await rolemenuRepository.AddRanges(rolemenus);
            result.Code = APIEnum.添加成功;
            result.Msg = APIEnum.添加成功.ToString();
            result.data = res;
            return await  Task.FromResult(result);
        }
    }
}
